package com.Long.dtx.seatademo.bank1.service.serviceIml;

import com.Long.dtx.seatademo.bank1.dao.AccountInfoDao;
import com.Long.dtx.seatademo.bank1.entity.AccountChangeEvent;
import com.Long.dtx.seatademo.bank1.service.AccountInfoService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author GL
 * @version 1.0
 * @date 2021/4/20 22:51
 */
@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {
    @Resource(name = "rocketMQTemplate")
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private AccountInfoDao accountInfoDao;


    /*
     * 向MQ发送一条事务消息
     *
     * */
    @Override
    public void sendUpdateAccountBalance(AccountChangeEvent accountChangeEvent) {

        JSONObject jsonObject = new JSONObject();
        //将accountChange转换为change
        jsonObject.put("accountChange", accountChangeEvent);
        String jsonString = jsonObject.toJSONString();
        //生成Message类型
        Message<String> msg = MessageBuilder.withPayload(jsonString).build();
        //发送一条事务消息
        log.info("开始发送消息");
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction("producer_group_txms_bank1", "topic_txMms", msg, null);
        log.info("发送完毕,结果：{}",transactionSendResult.toString());

    }

    /*消息消费成功后会执行成功*/
    @Override
    public void doUpdateAccountBalance(AccountChangeEvent accountChangeEvent) {
        //幂等判断
        if (accountInfoDao.isExistTx(accountChangeEvent.getTxNo()) > 0) {
            return;
        }
        accountInfoDao.updateAccountBalance(accountChangeEvent.getAccountNo(), accountChangeEvent.getAmount());
        /*
        添加事务日志
        * */
        accountInfoDao.addTx(accountChangeEvent.getTxNo());

    }

    public static void main(String[] args) {



    }
}
